/*
 * EchoServer.h
 * 
 * 使用 BaseServer 框架的 Echo 服务器
 * 阶段3：展示框架的易用性
 * 
 * 用户只需：
 * 1. 继承 BaseServer
 * 2. 实现 onInit() 注册消息处理器
 * 3. 实现消息处理函数
 */

#pragma once

#include "server/BaseServer.h"
#include "protocol/PacketHeader.h"
#include "echo.pb.h"

namespace servers {

/**
 * @brief Echo 服务器
 * 
 * 功能：
 * 1. 接收客户端的 EchoRequest
 * 2. 返回 EchoResponse（回显消息+时间戳）
 */
class EchoServer : public framework::BaseServer {
public:
    explicit EchoServer(const framework::ServerConfig& config)
        : BaseServer(config) {}
    
protected:
    /**
     * @brief 初始化 - 注册消息处理器
     */
    bool onInit() override {
        // 注册 EchoRequest 处理器
        registerMessageHandler<protocol::EchoRequest>(
            protocol::MSG_ECHO_REQUEST,
            std::bind(&EchoServer::onEchoRequest, this, 
                     std::placeholders::_1, 
                     std::placeholders::_2, 
                     std::placeholders::_3));
        
        LOG_INFO << "EchoServer: Message handlers registered";
        return true;
    }
    
    /**
     * @brief 启动后回调
     */
    void onStart() override {
        LOG_INFO << "EchoServer started successfully!";
        LOG_INFO << "Ready to accept connections...";
    }
    
    /**
     * @brief 会话连接回调
     */
    void onSessionConnected(const framework::SessionPtr& session) override {
        LOG_INFO << "New client connected: " << session->sessionId();
    }
    
    /**
     * @brief 会话断开回调
     */
    void onSessionDisconnected(const framework::SessionPtr& session) override {
        LOG_INFO << "Client disconnected: " << session->sessionId();
    }

private:
    /**
     * @brief 处理 Echo 请求
     */
    void onEchoRequest(const framework::SessionPtr& session,
                      const protocol::EchoRequest& request,
                      muduo::Timestamp time) {
        LOG_INFO << "Session " << session->sessionId() 
                 << " echo request: " << request.message();
        
        // 构造响应
        protocol::EchoResponse response;
        response.set_message(request.message());
        response.set_timestamp(time.microSecondsSinceEpoch());
        
        // 发送响应
        sendToClient(session->sessionId(), protocol::MSG_ECHO_RESPONSE, response);
        
        LOG_DEBUG << "Echo response sent to session " << session->sessionId();
    }
};

} // namespace servers

